1. What are subroutines in Fortran?
Subroutines in Fortran are reusable blocks of code that perform specific tasks. They allow you to modularize your code by separating different functionalities into smaller, more manageable units. Subroutines can accept input parameters and return values, but they cannot be called recursively.
2. What are functions in Fortran?
Functions in Fortran are similar to subroutines but are specifically designed to return a single value. They are useful for encapsulating algorithms or computations that produce a result. Functions can accept input parameters, perform calculations, and return a result to the calling code.
Here's an example of a subroutine and a function:
module example_mod
implicit none
contains
subroutine my_subroutine(x)
real, intent(in) :: x
print *, 'Inside subroutine:', x
end subroutine my_subroutine
function my_function(x, y)
real :: my_function
real, intent(in) :: x, y
my_function = x**2 + y**2
end function my_function
end module example_mod
program subroutine_function_example
use example_mod
implicit none
real :: a, b, result
a = 3.0
b = 4.0
call my_subroutine(a)
result = my_function(a, b)
print *, 'Result from function:', result
end program subroutine_function_example
This program demonstrates the usage of a subroutine (my_subroutine
) and a function (my_function
) to perform specific tasks.